package com.dgut.crm.system.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.dgut.crm.system.dao.DepartmentRepository;
import com.dgut.crm.system.entity.Department;
import com.dgut.crm.system.entity.dto.DepartmentNameDTO;

@Service
@Transactional
public class DepartmentService implements IDepartmentService
{
	@Autowired
	private DepartmentRepository departmentRepository;

	public void saveOrUpdate(Department department) {
		departmentRepository.save(department);
	}
	public void delete(Department department) {
		departmentRepository.delete(department);
	}

	@Transactional(readOnly = true)
	public Department findOne(Long id) {
		return departmentRepository.findOne(id);
	}
	@Transactional(readOnly = true)
	public List<Department> findAll() {
		return (List<Department>) departmentRepository.findAll();
	}
	@Transactional(readOnly = true)
	public Page<Department> findAll(Specification<Department> spec, Pageable pageable) {
		return departmentRepository.findAll(spec, pageable);
	}
	@Override
	public void deleteDepartments(List<Long> ids) {
		// TODO Auto-generated method stub
		// TODO Auto-generated method stub
		List<Department> departments = (List<Department>) departmentRepository.findAll(ids);
			if(departments != null) {
				departmentRepository.delete(departments);
		}
	}
	@Override
	public Department findOne(String name) {
		return departmentRepository.findByName(name);
	}
	@Override
	public List<DepartmentNameDTO> findNameAll() {
		// TODO Auto-generated method stub
		List<Department> list = (List<Department>) departmentRepository.findAll();
		List<DepartmentNameDTO> dtoLists = new ArrayList<DepartmentNameDTO>();
		for (Department d : list) {
			DepartmentNameDTO dto = new DepartmentNameDTO();
			dto.setId(d.getId());
			dto.setName(d.getName());
			dtoLists.add(dto);
		}
		return dtoLists;
	}
}
